package com.banach.prema.im.util;

import com.alibaba.fastjson.JSONObject;
import com.banach.prema.im.config.AppConfig;
import com.banach.prema.im.config.TlsConfig;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class RestApiUtils {
	@Resource
	private AppConfig appConfig;
	@Resource
	private TlsConfig tlsConfig;

	private RestTemplate restTemplate = new RestTemplate();
	private Logger log = LoggerFactory.getLogger(RestApiUtils.class);


	public JSONObject doPost(String item,JSONObject bodyData){
		log.info("RestApi请求数据："+bodyData.toJSONString());
		String usersig = tlsConfig.getUsersig(appConfig.getIdentifier());
		String reqUrl = appConfig.getUrl();
		if(item.startsWith("/")){
			reqUrl += item;
		}else {
			reqUrl += "/"+item;
		}
		reqUrl += "?sdkappid="+appConfig.getSdkAppId()+"&identifier="+appConfig.getIdentifier()+"&usersig="+usersig+"&random="+ CommonUtils.getRdm(8)+"&contenttype=json";
		try {
			ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(reqUrl,bodyData,JSONObject.class);
			log.info("RestApi请求回应数据："+responseEntity.getBody().toJSONString());
			return responseEntity.getBody();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public AppConfig getAppConfig() {
		return appConfig;
	}

	public void setAppConfig(AppConfig appConfig) {
		this.appConfig = appConfig;
	}
	
}
